package com.travel.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.qianfeng.util.ResultMsg;
import com.travel.entity.TbHomeOrder;
import com.travel.entity.TbTripOrder;
import com.travel.service.HomeOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

@Component
public class ALiPayTools {


    @Autowired
    HomeOrderService homeOrderService;

    @Autowired
    payBackController payBackController;

    public static String app_id = "9021000129657693";
    public static String private_key = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCTdF/sJKGuQIFettu9G6BZ8hRg4U/U1IdHdApbrYrVfWzHLORupWzrgngBzhOJK4/gHEb8wa/E62/dGQcggdjuoB7XTBUgP67WqO+2ClSykGqsjjc4gFMjFBIjE1ncHaHpqyP1diSzA8pHUlaY7YqkJZd6ndYwcJ6usJdLu6MPEgZNXM/aBw1LQl5DsqKfjK4qUtB44KmCV5iPtdzMwiikJbf8QthqN4QGbDWAOE21eMnt+URNmhnPvJ9It7PZNCqXNqMXfDEir/uYHsWYsH0FM0OIARrIqwLJeMdePLF9sW/8vNB3yQUlg4V3OPs/veXmqIHFy6DsynTHCBTiQOezAgMBAAECggEBAI7k2ggnv57z1+sHXY63dP91PxZbgleH1ckCxP7vAHm/YGjsMjqfiRv5hX6KTBhD5NuTy58pu8IjPnaOyH9SFf25oemWS2rDDBXuBM7u2AFrPlUWRKE2ilqWGrVvDUfoV33wYZp/8TSh2aagPldY62ADJfanemfa24wCibvUjEIPBc5r9Gzslmch8KReOjeRxpT1P9qtu+46AK0ZRzJQ6jrBVZo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grBlAJnxYabUpMq7dlDgilkiLKhmTpGk7C2jRrXS8GYtYR224pBRcMXDVro+zTYoCTJpDL4VyubWO7kT6OChAJQB80bifBcVV7PNhQDCzMjOWwiM6/l/jwccq+Ph4fBh/AgEt2aZS7GUE3MCsAUmlsWVc/Kgt1unYl6YoVnVZJBHDVbzeAvwshjYloKHGrS9pXPGIR5ZIQmuc4V2YUydhRd0z6FzGAYMS8EeOvBpw8Sw5L2Joh8H0blAhApHi+ef9t4gj8KepiIJZG3qoWXIhu3ELAawPY1x8D2TZMkoQ5B4l3CdHVPKGbu+3qVAeg/s4U4TsZcDz3mtWswIDAQAB";

    public static AlipayClient alipayClient = new DefaultAlipayClient("https://openapi-sandbox.dl.alipaydev.com/gateway.do",app_id,private_key,"json","UTF-8",alipay_public_key,"RSA2");

    // 创建AlipayTradeQueryRequest对象
    public static AlipayTradeQueryRequest request1 = new AlipayTradeQueryRequest();
    // 发起支付宝交易查询请求
    public static AlipayTradeQueryResponse response1;

    static {
        try {
            response1 = alipayClient.execute(request1);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
    }


    public static ResultMsg pay(Object obj) throws AlipayApiException {
        String out_trade_no = null;
        BigDecimal total_amount = null;
        String subject = null;
        if (obj instanceof TbHomeOrder){
            TbHomeOrder homeOrder = (TbHomeOrder) obj;

            out_trade_no = homeOrder.getHomeOrderId();
            total_amount = homeOrder.getHomeOrderPrice();
            subject = homeOrder.getHomeOrderName();
        }
        if (obj instanceof TbTripOrder){
            TbTripOrder tripOrder = (TbTripOrder) obj;

            out_trade_no = tripOrder.getTripTicketId();
            total_amount = tripOrder.getTripTicketTotal();
            subject = tripOrder.getTripTicketFlag();
        }

        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        request.setNotifyUrl("http://quq6dx.natappfree.cc/pay/pay");
        JSONObject bizContent = new JSONObject();
//        bizContent.put("out_trade_no", "20210817010101003");
        bizContent.put("out_trade_no", out_trade_no);
        bizContent.put("total_amount", total_amount);
        bizContent.put("subject", subject);

        request.setBizContent(bizContent.toString());
        AlipayTradePrecreateResponse response = alipayClient.execute(request);
        if(response.isSuccess()){
            System.out.println("调用成功，二维码链接：" + response.getQrCode());
            QrCodeUtil.generate(response.getQrCode(), 300, 300, FileUtil.file("./qrcode.jpg"));

            try {
                int mark = 0;
                while (true){
                    mark++;
                    if (mark==12){
                        response1.setTradeStatus("TRADE_CLOSED");
                    }
                    Thread.sleep(5000);
                    // 获取支付状态
                    String tradeStatus = response1.getTradeStatus();

                    // 处理支付状态，根据需要进行业务逻辑处理
                    if ("TRADE_SUCCESS".equals(tradeStatus)) {
                        // 交易支付成功
                        System.out.println("支付成功");
                        return ResultMsg.success();
                    } else if ("TRADE_CLOSED".equals(tradeStatus)) {
                        // 交易已关闭
                        System.out.println("交易已关闭");
                        break;
                    } else if ("TRADE_FINISHED".equals(tradeStatus)) {
                        // 交易已结束
                        System.out.println("交易已结束");
                        break;
                    } else {
                        // 交易支付处理中或者交易状态未知
                        System.out.println("交易处理中");
                    }
                }

            } catch (Exception e) {
                // 处理异常
                e.printStackTrace();
            }
        }
        else {
            System.out.println("调用失败，错误信息：" + response.getSubMsg());
        }
        return ResultMsg.error(350,"支付中断！");
    }

}
